/**
 * @Time    : 2021/03/09 14:38
 * @Author  : WanRongJia
 * @License : Software business license
 * @Site    : www.linshensjl.top
 * @File    : db.js
 * @Software: Rich Web Platform
 * @Function: 数据库连接方法
 * @Version : 1.0
 **/

const mongoose = require('mongoose');
let logger = require('log4js').getLogger("default");

mongoose.promise = global.Promise;

const connect = () => {
    console.log(process.env.DATABASE_URL)
    mongoose.connect(
        process.env.DATABASE_URL,
        // {autoReconnect:true,poolSize:5,keepAlive: true,useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true},
        err => {
            let dbStatus = ''
            if (err) {
                dbStatus = `*    Error connecting to DB: ${err}\n****************************\n`
                logger.error(dbStatus);
                return;
            }
            dbStatus = `*    DB Connection: OK\n****************************\n`
            if (process.env.NODE_ENV !== 'test') {
                console.log('****************************')
                console.log('*    Starting Server')
                console.log(`*    Port: ${process.env.PORT || 3000}`)
                console.log(`*    NODE_ENV: ${process.env.NODE_ENV}`)
                console.log(`*    Database: MongoDB`)
                console.log(dbStatus)
                logger.info(dbStatus);
            }
        }
    );
}

connect();
mongoose.set('debug', true);//开发的时候打开mongodb的语句调试
mongoose.connection.on('error', console.log)
mongoose.connection.on('disconnected', connect)

module.exports = { mongoose, connect };
